import React, { Component } from 'react';
import { connect } from 'dva';
import { Table, Input, Select, Button, Icon, Pagination, Modal, message } from 'antd';
import styles from '../userManage/index.css';
import { Dispatch, AnyAction } from 'redux';
import { produce, Draft } from 'immer';
import {
  queryPower,
  queryChildPower,
  addChildPower,
  deletePower,
  matchChildsByParents,
} from '@/services/systemDevice';
import { Statistics } from '@/models/connect';
import { FormComponentProps } from 'antd/es/form';
import { router } from 'umi';
import _ from 'lodash';
import e from 'express';
import { isMenuVisible } from '@/utils/utils';
const { Option } = Select;

interface powerPsops extends FormComponentProps {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  // childList?: Statistics;
  form: FormComponentProps['form'];
}
interface powerManager {
  pageTotal: number;
  filterQueryParams: any;
  title: any;
  params: any;
  showModel: boolean;
  kinds: any;
  list: any;
  isTrue: boolean;
  id: any;
  childListPower: any;
  deviceName: any;
  powerParams: any;
  filterQueryParams1: any;
  params1: any;
  selectedRowKeys: any;
}
class powerManage extends Component<powerPsops, powerManager> {
  state: powerManager = {
    title: '', //删除内容提示
    filterQueryParams: {
      deviceType: undefined, // 资产种类
      deviceParentType: undefined, // 资产类别
      deviceName: '',
      pageNum: 1,
      pageSize: 10,
      roleId: this.props.match.params.roleId,
    },
    filterQueryParams1: {
      deviceType: undefined, // 资产种类
      deviceParentType: undefined, // 资产类别
      deviceName: '',
      pageNum: 1,
      pageSize: 10,
      roleId: this.props.match.params.roleId,
    },
    params: {
      deviceParentType: null,
    },
    params1: {
      deviceParentType: null,
    },
    powerParams: {
      roleDeviceIdList: [],
      sreRoleId: this.props.match.params.roleId,
    },
    showModel: false,
    isTrue: false,
    list: {},
    childListPower: {},
    id: [],
    selectedRowKeys: [],
  };
  async componentWillMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'statistics/longDeviceType' });
    dispatch({ type: 'device/clearChildren' });
    this.handleFilterQuery();
  }
  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 资产名称
    e.persist();
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.filterQueryParams.deviceName = e.target.value;
      }),
    );
  };
  handleChangeType = (e: number) => {
    // 资产种类
    if (!this.state.filterQueryParams.deviceParentType) {
      message.info('请先选择所属类别');
      return;
    } else {
      this.setState(
        produce((draft: Draft<powerManager>): void => {
          draft.filterQueryParams.deviceType = e;
          //   draft.kinds = draft.filterQueryParams.deviceType;
        }),
      );
    }
  };
  handleChangeCategory = (e: number) => {
    // 资产类别
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.filterQueryParams.deviceParentType = e;
        draft.filterQueryParams.deviceType = '';
        draft.params.deviceParentType = e;
      }),
    );
    const { dispatch } = this.props;
    if (e) {
      dispatch({ type: 'device/matchChildsByParents', payload: { deviceTypeNo: e } });
    } else {
      dispatch({ type: 'device/clearChildren' });
    }
    // this.deviceKindsSelect();
  };
  handleChangeBase = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 资产名称
    e.persist();
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.filterQueryParams1.deviceName = e.target.value;
      }),
    );
  };
  handleChangeTypeBase = (e: number) => {
    // 资产种类
    if (!this.state.filterQueryParams1.deviceParentType) {
      // alert('')
      message.info('请先选择所属类别');
      return;
    } else {
      this.setState(
        produce((draft: Draft<powerManager>): void => {
          draft.filterQueryParams1.deviceType = e;
          //   draft.kinds = draft.filterQueryParams.deviceType;
        }),
      );
    }
  };
  handleChangeCategoryBase = (e: number) => {
    // 资产类别
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.filterQueryParams1.deviceParentType = e;
        draft.filterQueryParams1.deviceType = '';
        draft.params1.deviceParentType = e;
      }),
    );
    const { dispatch } = this.props;
    if (e) {
      dispatch({ type: 'device/matchChildsByParents', payload: { deviceTypeNo: e } });
    } else {
      dispatch({ type: 'device/clearChildren' });
    }
    // this.deviceKindsSelect();
  };
  // 页码变化
  // handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {

  // };
  // // 页码变化
  // handlePageChange1: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
  //   this.setState(
  //     produce((draft: Draft<powerManager>): void => {
  //       draft.filterQueryParams1.pageNum = pageNum;
  //     }),
  //     () => this.handleFilterQuery1(),
  //   );
  // };
  handleFilterQuery = async () => {
    // 搜索
    // const { dispatch } = this.props;
    const [err, data] = await queryPower(this.state.filterQueryParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<powerManager>): void => {
          draft.list = data;
        }),
      );
    }
    // console.log(this.state.deptList);
    // dispatch({ type: 'systemDevice/deptList', payload: this.state.filterQueryParams });
  };
  handleFilterQuery1 = async () => {
    // 搜索
    const [err, data] = await queryChildPower(this.state.filterQueryParams1);
    if (!err) {
      this.setState(
        produce((draft: Draft<powerManager>): void => {
          draft.childListPower = data;
          draft.powerParams.roleDeviceIdList = [];
        }),
      );
    }
  };
  handleSure = async () => {
    // 确认删除
    console.log(this.state.list.rows);
    if(this.state.list.rows.length === 1){
      this.setState(
        produce((draft: Draft): void => {
          draft.filterQueryParams.pageNum = draft.filterQueryParams.pageNum - 1;
          // draft.pageNum = draft.parameters.pageNum;
        })
      );
    }
    const [err, data] = await deletePower({ str: this.state.id });
    if (!err) {
      this.setState(
        produce((draft: Draft<powerManager>): void => {
          draft.isTrue = false;
        }),
      );
      message.info('删除成功');
    } else {
      this.setState(
        produce((draft: Draft<powerManager>): void => {
          draft.isTrue = false;
        }),
      );
    }
    this.handleFilterQuery();
  };
  handleSigDelete = (record: any) => {
    // 删除
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.id = record.roleDevicePowerId;
      }),
    );
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.title = '确定要删除选中数据吗？';
        draft.isTrue = true;
      }),
    );
  };
  handleAddDept = async () => {
    //新增
    const { dispatch } = this.props;
    dispatch({ type: 'device/clearChildren' });
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.showModel = true;
        draft.filterQueryParams1.pageNum = 1;
        draft.filterQueryParams1.deviceParentType = undefined;
        draft.filterQueryParams1.deviceType = undefined;
      }),
    );
    this.handleFilterQuery1();
  };
  handleSubmit = async (e: any) => {
    // 确认新增
    // console.log(this.state.powerParams);
    if (this.state.powerParams.roleDeviceIdList.length !== 0) {
      //有数据的时候调用接口
      const [err, data] = await addChildPower(this.state.powerParams);
      if (!err) {
        this.setState(
          produce((draft: Draft<powerManager>): void => {
            // draft.showModel = false;
            draft.selectedRowKeys = [];
            draft.filterQueryParams1.pageNum = 1;
          }),
        );
        message.info('添加成功');
        this.handleFilterQuery1();
        this.handleFilterQuery();
      }
    } else {
      message.info('请添加数据');
    }
  };
  handleSigAdd = (record: any) => {
    //添加设备编号
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.powerParams.roleDeviceIdList.push({
          deviceId: record.deviceId,
          roleDevicePowerId: '',
        });
      }),
    );
    setTimeout(async () => {
      const [err, data] = await addChildPower(this.state.powerParams);
      if (!err) {
        message.info('添加成功');
        this.setState(
          produce((draft: Draft<powerManager>): void => {
            draft.powerParams.roleDeviceIdList = [];
          }),
        );
        this.handleFilterQuery1();
      }
    }, 0);
  };
  columns: any = [
    {
      title: '资产编号',
      dataIndex: 'deviceId',
      key: 'deviceId',
    },
    {
      title: '资产名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '资产类别',
      dataIndex: 'deviceTypeParentName',
      key: 'deviceTypeParentName',
    },
    {
      title: '资产种类',
      dataIndex: 'deviceTypeName',
      key: 'deviceTypeName',
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'sdtCreateTime',
    //   key: 'sdtCreateTime',
    // },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          <span className={styles.one}>
            {isMenuVisible('system:roleDevicePower:remove') && (
              <a
                onClick={() => {
                  this.handleSigDelete(record);
                }}
              >
                删除
              </a>
            )}
          </span>
        );
      },
    },
  ];
  childColumns: any = [
    {
      title: '资产编号',
      dataIndex: 'deviceId',
      key: 'deviceId',
    },
    {
      title: '资产名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '资产类别',
      dataIndex: 'deviceTypeParentName',
      key: 'deviceTypeParentName',
    },
    {
      title: '资产种类',
      dataIndex: 'deviceTypeName',
      key: 'deviceTypeName',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          <span className={styles.one}>
            <a
              onClick={() => {
                this.handleSigAdd(record);
              }}
            >
              添加
            </a>
          </span>
        );
      },
    },
  ];
  onSelectChange = (selectedRowKeys: any, selectedRows: any) => {
    // console.log('selectedRowKeys changed: ', selectedRows);
    this.setState({ selectedRowKeys });
    this.setState(
      produce((draft: Draft<powerManager>): void => {
        draft.powerParams.roleDeviceIdList = selectedRows.map((
          e: any, //
        ) => ({ deviceId: e.deviceId, roleDevicePowerId: '' }));
      }),
    );
  };
  render() {
    const { longDeviceType = [], childList = [] } = this.props;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div className={`${styles.container} ${styles.dataContainer}`}>
        <div className={styles.containerTitle}>位置: 角色管理/设备权限</div>
        <div className={styles.userRight}>
          <div style={{ overflow: 'hidden' }}>
            <div className={styles['inforAnasy-container-top-btn']}>
              {isMenuVisible('system:roleDevicePower:add') && (
                <Button type="link" onClick={this.handleAddDept}>
                  <Icon type="plus" />
                  新增
                </Button>
              )}
              <Button type="link" onClick={() => router.push('/system')}>
                <Icon type="rollback" />
              </Button>
            </div>
            <div style={{ display: 'flex' }}>
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleChange}
                  value={this.state.filterQueryParams.deviceName}
                  addonBefore="资产名称"
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>资产类别</span>
                <Select
                  style={{ width: 200 }}
                  allowClear={true}
                  placeholder="请选择资产类别"
                  onChange={this.handleChangeCategory}
                  value={this.state.filterQueryParams.deviceParentType}
                >
                  {/* <Option value="">请选择</Option> */}
                  {_.map(longDeviceType, (item: any, index: number) => (
                    <Option key={index} value={item.deviceTypeNo}>
                      {item.deviceTypeName}
                    </Option>
                  ))}
                </Select>
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>资产种类</span>
                <Select
                  allowClear={true}
                  value={this.state.filterQueryParams.deviceType}
                  style={{ width: 200 }}
                  placeholder="请先选择资产类别"
                  onChange={this.handleChangeType}
                >
                  {_.map(childList, (item: any, index: number) => (
                    <Option key={index} value={item.deviceTypeNo}>
                      {item.deviceTypeName}
                    </Option>
                  ))}
                </Select>
              </div>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.pageNum = 1;
                    }),
                    () => {
                      this.handleFilterQuery();
                    },
                  );
                }}
              >
                搜索
              </Button>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.deviceParentType = undefined;
                      draft.filterQueryParams.deviceType = undefined;
                      draft.filterQueryParams.deviceName = '';
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <Table
            scroll={{ y: '500px' }}
            pagination={false}
            columns={this.columns}
            dataSource={this.state.list.rows}
            // rowKey="deviceId"
          />
          <div className="pagination-box">
            <Pagination
              defaultCurrent={this.state.filterQueryParams.pageNum}
              current={this.state.filterQueryParams.pageNum}
              onChange={pagenum => {
                this.setState(
                  produce((draft: Draft<powerManager>): void => {
                    draft.filterQueryParams.pageNum = pagenum;
                  }),
                  () => this.handleFilterQuery(),
                );
              }}
              total={this.state.list.total ? this.state.list.total : 0}
            />
            <span className="pagination-title-box">
              第{this.state.filterQueryParams.pageNum}/
              {Math.ceil(
                (this.state.list.total ? this.state.list.total : 0) /
                  this.state.filterQueryParams.pageSize,
              )}
              页 共{this.state.list.total ? this.state.list.total : 0}条
            </span>
          </div>
          <Modal
            title="新增设备"
            visible={this.state.showModel}
            className="porwer-modal"
            footer={null}
            onCancel={() => {
              this.setState({
                showModel: false,
                filterQueryParams1: {
                  deviceParentType: undefined,
                  deviceType: undefined,
                  roleId: this.props.match.params.roleId,
                  pageNum: 1,
                  pageSize: 10,
                },
                powerParams: {
                  roleDeviceIdList: [],
                  sreRoleId: this.props.match.params.roleId,
                },
                selectedRowKeys: [],
              });
              this.handleFilterQuery();
            }}
          >
            <div style={{ overflow: 'hidden' }}>
              {/* <div className={styles['inforAnasy-container-top-btn']}>
                        <Button type="link" onClick={this.handleAddDept}>
                            <Icon type="plus" />
                            批量添加
                        </Button>
                    </div> */}
              <div style={{ display: 'flex' }}>
                <div className={styles['dev-search-select']}>
                  <Input
                    onChange={this.handleChangeBase}
                    value={this.state.filterQueryParams1.deviceName}
                    addonBefore="资产名称"
                    type="text"
                  />
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>资产类别</span>
                  <Select
                    style={{ width: 200 }}
                    allowClear={true}
                    placeholder="请选择资产类别"
                    onChange={this.handleChangeCategoryBase}
                    value={this.state.filterQueryParams1.deviceParentType}
                  >
                    {/* <Option value="">请选择</Option> */}
                    {_.map(longDeviceType, (item: any, index: number) => (
                      <Option key={index} value={item.deviceTypeNo}>
                        {item.deviceTypeName}
                      </Option>
                    ))}
                  </Select>
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>资产种类</span>
                  <Select
                    allowClear={true}
                    value={this.state.filterQueryParams1.deviceType}
                    style={{ width: 200 }}
                    placeholder="请先选择资产类别"
                    onChange={this.handleChangeTypeBase}
                  >
                    {_.map(childList, (item: any, index: number) => (
                      <Option key={index} value={item.deviceTypeNo}>
                        {item.deviceTypeName}
                      </Option>
                    ))}
                  </Select>
                </div>
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams.pageNum = 1;
                      }),
                      () => {
                        this.handleFilterQuery1();
                      },
                    );
                  }}
                >
                  搜索
                </Button>
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams1.deviceParentType = undefined;
                        draft.filterQueryParams1.deviceType = undefined;
                        draft.filterQueryParams1.deviceName = '';
                      }),
                    );
                  }}
                >
                  重置
                </Button>
              </div>
            </div>
            <div className={styles.childName}>
              <Table
                scroll={{ y: '220px' }}
                pagination={false}
                columns={this.childColumns}
                dataSource={this.state.childListPower.rows}
                rowSelection={rowSelection}
              />
            </div>
            <div className="pagination-box">
              <Pagination
                defaultCurrent={this.state.filterQueryParams1.pageNum}
                current={this.state.filterQueryParams1.pageNum}
                onChange={pagenum => {
                  this.setState(
                    produce((draft: Draft<powerManager>): void => {
                      draft.filterQueryParams1.pageNum = pagenum;
                      draft.selectedRowKeys = [];
                    }),
                    () => this.handleFilterQuery1(),
                  );
                }}
                total={this.state.childListPower.total ? this.state.childListPower.total : 0}
              />
              <span className="pagination-title-box">
                第{this.state.filterQueryParams1.pageNum}/
                {Math.ceil(
                  (this.state.childListPower.total ? this.state.childListPower.total : 0) /
                    this.state.filterQueryParams1.pageSize,
                )}
                页 共{this.state.childListPower.total ? this.state.childListPower.total : 0}条
              </span>
            </div>
            <div className={styles.footBtnArea}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSubmit}
              >
                批量添加
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({
                    showModel: false,
                    powerParams: {
                      roleDeviceIdList: [],
                      sreRoleId: this.props.match.params.roleId,
                    },
                    selectedRowKeys: [],
                  });
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams1.deviceParentType = undefined;
                      draft.filterQueryParams1.deviceType = undefined;
                      draft.filterQueryParams1.deviceName = '';
                    }),
                  );
                  this.handleFilterQuery();
                }}
              >
                取消
              </div>
            </div>
          </Modal>
          <Modal
            title="系统提示"
            className={`${styles.modal} ${styles.deleteBox}`}
            visible={this.state.isTrue}
            onCancel={() => {
              this.setState({ isTrue: false });
            }}
          >
            <div className={styles.titles}>{this.state.title}</div>
            <div className={styles.footBtn}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSure}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ isTrue: false });
                }}
              >
                取消
              </div>
            </div>
          </Modal>
        </div>
      </div>
    );
  }
}
// export default Form.create<powerPsops>()(powerManage);
export default connect(({ loading, statistics, device }: any) => {
  return {
    loading: loading.effects['statistics/deviceList'],
    longDeviceType: statistics.longDeviceType,
    childList: device.matchChildsByParents,
  };
})(powerManage);
